// pages/goods/detail/index.js
import { getGoodsInfo } from '../../../api/goods'
import { addCart, getCartList } from '@/api/cart'
import { userbehavior } from '../../../behaviors/userbehaviors'
Page({
  // 页面的初始数据
  behaviors:[userbehavior],
  data: {
	  goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    allCount: '',
    buyNow: 0
  },
  async getGoodsData(){
    const { data } = await getGoodsInfo(this.goodsId)
    this.setData({goodsInfo:data})
  },
  // 加入购物车
  handleAddcart() {
    this.setData({show: true, buyNow: 0})
  },
  // 立即购买
  handeGotoBuy() {
    this.setData({show: true,buyNow: 1})
  },
  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({ show: false })
  },
  async determine(){
    const { token, count, blessing, buyNow } = this.data
    const goodsId = this.goodsId
    if(!token){
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return
    }
    this.setData({ show: false })
    if(buyNow === 0){
      const { code } = await addCart({goodsId,count,blessing})
      if(code === 200){
        wx.toast({
          title: "加入购物车成功"
        })
        this.getCartnum()
      }
    }
    else{
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`
      })
    }
  },
  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    this.setData({count: event.detail})
  },
  previewImage(){
    wx.previewImage({
      urls: this.data.goodsInfo.detailList
    })
  },
  async getCartnum(){
    if(!this.data.token) return
    const { code,data } = await getCartList()
    if(data.length){
      let allCount = 0
      data.forEach(itme => {
        allCount += itme.count
      })
      this.setData({ 
        // (allCount > 99? '99+': allCount) + ''
        allCount: allCount > 99? '99+': allCount
      })
    }
  },
  onLoad(options){
    this.goodsId = options.goodsId
    this.getGoodsData()
    this.getCartnum()
  },
  onShareAppMessage(){
    return {
      title: this.data.goodsInfo.floralLanguage,
      path: "/modules/goodModule/pages/goods/detail/detail",
      imageUrl: this.data.goodsInfo.imageUrl
    }
  },
  onShareTimeline(){
    return {
      title: this.data.goodsInfo.floralLanguage,
      imageUrl: this.data.goodsInfo.imageUrl
    }
  }
})
